package com.listener.testlistener;

import jakarta.servlet.ServletRequestEvent;
import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpServletRequest;

import java.util.logging.Level;
import java.util.logging.Logger;

@WebListener("/")
public class RequestLoggingListener implements jakarta.servlet.ServletRequestListener {
    private static final Logger LOGGER = Logger.getLogger(RequestLoggingListener.class.getName());

    @Override
    public void requestInitialized(ServletRequestEvent sre){
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        long startTime = System.currentTimeMillis();

        String clientIp = request.getRemoteAddr();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString() != null ? "?" + request.getQueryString() : "";
        String userAgent = request.getHeader("User-Agent");

        LOGGER.log(Level.INFO, "Request Start - " +
                "Time: " + startTime + ", " +
                "Client IP: " + clientIp + ", " +
                "Method: " + method + ", " +
                "URI: " + uri + queryString + ", " +
                "User-Agent: " + userAgent);

        System.out.println("Request Start - " +
                "Time: " + startTime + ", " +
                "Client IP: " + clientIp + ", " +
                "Method: " + method + ", " +
                "URI: " + uri + queryString + ", " +
                "User-Agent: " + userAgent);

        // 将请求属性中的 startTime 存储起来，以便稍后使用
        request.setAttribute("startTime", startTime);
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre){
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        long startTime = (Long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        long processingTime = endTime - startTime;

        LOGGER.log(Level.INFO, "Request Completed - " +
                "Processing Time: " + processingTime + "ms");
    }
}
